import React, { useState } from "react";
import { Avatar, Icon, Modal } from "antd";
import cls from "classnames";
import { format } from "timeago.js";

import style from "./index.module.scss";
import { EditBlock } from "./editor-block";

const colors = [
  "#52c41a",
  "#f5222d",
  "#1890ff",
  "#faad14",
  "#ff0064",
  "#722ed1",
];
// 获取随机颜色
const getColor = (() => {
  let cache = {};
  return (key: string) => {
    if (!cache[key]) {
      cache[key] = colors[Math.floor(Math.random() * colors.length)];
    } else {
      cache[key];
    }
    return cache[key];
  };
})();
export const CommentItem = ({
  comment,
  subComment = [],
  isInHostPage,
  hostId,
  parentComment,
  isChildren,
}) => {
  const [replyComment, setreplyComment] = useState(null);

  const submit = () => {};
  return (
    <div className={style.commentItem}>
      <header className={style.header}>
        <Avatar style={{ backgroundColor: getColor(comment?.name) }}>
          {comment?.name?.charAt(0)?.toUpperCase()}
        </Avatar>
        <span className={style.name}>{comment.name}</span>
        {comment?.replyUserName && (
          <>
            <span className={style.text}>回复</span>
            <strong>{comment.replyUserName}</strong>
          </>
        )}
      </header>
      <main className={style.main}>
        <div
          dangerouslySetInnerHTML={{ __html: comment?.content }}
          className={cls("markdonw", style.content)}
        ></div>
        <div className={style.info}>
          <span>{comment?.userAgent}</span>
          <span className={style.time}>
            {format(comment.publishAt, "zh_CN")}
          </span>
          <span
            className={style.reply}
            onClick={() => {
              setreplyComment(comment);
              submit();
            }}
          >
            <Icon className={style.icon} type="message" />
            回复
          </span>
        </div>
        {subComment.length ? (
          <div className={style.subComment}>
            {subComment.map((c) => (
              <CommentItem
                key={c.id}
                comment={c}
                isInHostPage={isInHostPage}
                hostId={hostId}
                parentComment={comment}
                isChildren={true}
              />
            ))}
          </div>
        ) : null}
      </main>
      <Modal
        width={"80%"}
        bodyStyle={{ backgroundColor: "var(--bg-second)" }}
        footer={null}
        visible={!!replyComment}
        closable={true}
        onCancel={() => setreplyComment(null)}
      >
        <EditBlock
          parentComment={parentComment || comment}
          replyComment={replyComment}
          hostId={hostId}
          isHostInPage={isInHostPage}
          onReply={() => setreplyComment(null)}
        />
      </Modal>
    </div>
  );
};
